/*
 * @Description:
 * @Author: 亢超
 * @Date: 2024-07-09 19:31:21
 * @LastEditTime: 2024-10-28 17:34:59
 */
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { manageLogin, getManageInfo, logout } from '@/api/manage.js'
import {useRouter} from 'vue-router'
/**
 * 用户store 操作用户相关信息
 */
export const useUserStore = defineStore(
  'cp-user',
  () => {
    const router = useRouter()
    //存储token
    const token = ref('')
    //存储用户信息
    const userInfo = ref({})

    //账号密码登录
    const accountLogin = (data) => {
      return new Promise((resolve, reject) => {
        manageLogin(data)
          .then((res) => {
            if (res.code === 200) {
              //将token存起来
              token.value = res.data.token
            }
            resolve(res)
          })
          .catch((err) => reject(err))
      })
    }
    //获取用户信息
    const getUserInfo = () => {
      return new Promise((resolve, reject) => {
        getManageInfo()
          .then((res) => {
            if (res.code === 200) {
              userInfo.value = res.data.data
              resolve(res)
            }
          })
          .catch((err) => reject(err))
      })
    }
    //退出
    const logoutSystem = () => {
      return new Promise((resolve, reject) => {
        logout()
          .then((res) => {
            if (res) {
              userInfo.value = {}
              token.value = ''
router.push('/login')
              resolve(res)
            }
          })
          .catch((err) => reject(err))
      })
    }
    return {
      token,
      userInfo,
      accountLogin,
      getUserInfo,
      logoutSystem
    }
  },
  {
    //开启持久化
    persist: true
  }
)
